<template>
    <div class="course-table">
      <Nav />
      <Tit title="课程表" />
      <el-container style="position: fixed;top: 120px;left: 500px;">
    <el-text style="margin-left: 30px">课程学年学期:</el-text>
    <el-tree-select
        v-model="sel_cyear"
        :data="cyear"
        :render-after-expand="false"
        style="width: 180px;margin-left: 10px"
    />
    <el-button plain @click="fetchCourseSchedule" style="margin-left: 50px">
      查询
    </el-button>
  </el-container>
      <el-table
        class="table"
        :data="tableData"
        style="width: 100%"
        border
        :cell-style="cellStyle"
        :header-cell-style="headerCellStyle"
        :show-header="true"
        v-loading="isLoading"
        element-loading-text="正在加载课程表..."
      >
        <el-table-column
          label="节次 / 星期"
          width="100"
          prop="period"
          fixed
        >
          <template #default="scope">
            {{ scope.row.period }}
          </template>
        </el-table-column>
  
        <el-table-column
          v-for="day in days"
          :key="day.value"
          :label="day.label"
          :prop="day.value"
          width="150"
        >
          <template #default="scope">
            <div v-if="scope.row[day.value].length">
              <div
                v-for="(course, index) in scope.row[day.value]"
                :key="index"
                class="course-item"
                @click="openCourseDetails(course)"
                :title="`课程名称: ${course.c_name}，教师: ${course.t_name}，地点: ${course.c_address}`"
              >
                <strong>{{ course.c_name }}</strong><br />
                
              </div>
            </div>
            <div v-else class="empty-slot">-</div>
          </template>
        </el-table-column>
  
        <!-- 显示无数据时的空表格 -->
        <template #empty>
          <div class="empty-message">暂无课程安排</div>
        </template>
      </el-table>
    </div>

        <!-- 课程详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="课程详情"
      width="50%"
      :show-close="true"
      :before-close="handleClose"
    >
      <div v-if="selectedCourse">
        <p><strong>课程编号:</strong> {{ selectedCourse.c_no }}</p>
        <p><strong>课程名称:</strong> {{ selectedCourse.c_name }}</p>
        <p><strong>学分:</strong> {{ selectedCourse.c_credit }}</p>
        <p><strong>教师:</strong> {{ selectedCourse.t_name }}</p>
        <p><strong>时间:</strong> {{ selectedCourse.c_time }}</p>
        <p><strong>地点:</strong> {{ selectedCourse.c_address }}</p>
        
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </template>
  
  <script>
  import Nav from "../components/navigation_stu.vue";
  import Tit from "../components/title.vue";
  import axios from "axios";
  import { ElMessage } from "element-plus";
  
  export default {
    name: "CourseTable",
    components: {
      Tit,
      Nav,
    },
    data() {
      return {
        isLoading: false, // 添加加载状态
        days: [
          { label: "周一", value: "monday" },
          { label: "周二", value: "tuesday" },
          { label: "周三", value: "wednesday" },
          { label: "周四", value: "thursday" },
          { label: "周五", value: "friday" },
          { label: "周六", value: "saturday" },
          { label: "周日", value: "sunday" },
        ],
        periods: [
          { label: "第一节", value: "period1" },
          { label: "第二节", value: "period2" },
          { label: "第三节", value: "period3" },
          { label: "第四节", value: "period4" },
          { label: "第五节", value: "period5" },
          { label: "第六节", value: "period6" },
          { label: "第七节", value: "period7" },
          { label: "第八节", value: "period8" },
        ],
        tableData: [],
        
        sel_cyear:'',
        cyear,
        dialogVisible: false,
        selectedCourse: null,
        
      };
    },
    mounted() {
    //   this.fetchCourseSchedule();
      document.title = '管理员后台系统'; // 动态设置页面标题
      const token = localStorage.getItem('token'); // 确保 token 已正确存储
      const userNo = sessionStorage.getItem('UserNo'); // 确保 UserNo 已正确存储
      if (!token || !userNo) {
        alert('缺少必要的认证信息，请重新登录。');
        this.$router.push({ name: "Login" });
      }
    },
    methods: {
      async fetchCourseSchedule() {
        this.isLoading = true; // 开始加载
        try {
            const selectedCyear = String(this.cyear.find(item => item.value === this.sel_cyear)?.value);
            const token = localStorage.getItem('token'); // 确保 token 已正确存储
            const userNo = sessionStorage.getItem('UserNo'); // 确保 UserNo 已正确存储
            const response = await axios.post(`${import.meta.env.VITE_API_BASE_URL}/student/showSelectedCourse`, {
          selSno: userNo,
          selCyear: selectedCyear,
        }, {
          headers: {
            token: token,
            'Content-Type': 'application/json'
          },
        });
          const courses = response.data.data;
          console.log(courses);
          console.log(response.data.code);
          this.processCourseData(courses);
        } catch (error) {
          ElMessage.error("加载课程表失败");
          console.error(error);
          // 如果请求失败，仍然初始化空表格
          this.initializeEmptyTable();
        } finally {
          this.isLoading = false; // 结束加载
        }
      },
      processCourseData(courses) {
        if (!courses || courses.length === 0) {
          this.initializeEmptyTable();
          return;
        }
  
        // 初始化表格数据
        const data = this.periods.map((period) => {
          const row = { period: period.label };
          this.days.forEach((day) => {
            row[day.value] = [];
          });
          return row;
        });
  
        // 填充课程数据
        courses.forEach((course) => {
          const dayKey = this.getDayKey(course.c_time); // 根据课程时间获取星期key
          const periodKeys = this.getPeriodKeys(course.c_time); // 获取所有节次key
          if (dayKey && periodKeys.length > 0) {
            periodKeys.forEach((periodKey) => {
              const row = data.find(
                (r) => r.period === this.getPeriodLabel(periodKey)
              );
              if (row) {
                row[dayKey].push(course);
              }
            });
          }
        });
  
        this.tableData = data;
      },
      initializeEmptyTable() {
        this.tableData = this.periods.map((period) => {
          const row = { period: period.label };
          this.days.forEach((day) => {
            row[day.value] = [];
          });
          return row;
        });
      },
      getDayKey(timeStr) {
        // 解析时间格式 "周三1-2节"
        const dayMap = {
          "周一": "monday",
          "周二": "tuesday",
          "周三": "wednesday",
          "周四": "thursday",
          "周五": "friday",
          "周六": "saturday",
          "周日": "sunday",
        };
        const dayMatch = timeStr.match(/周[一二三四五六日]/);
        const day = dayMatch ? dayMatch[0] : null;
        return dayMap[day] || null;
      },
      getPeriodKeys(timeStr) {
        // 解析时间格式 "周三1-2节"
        const periodRegex = /(\d+)-(\d+)节/;
        const match = timeStr.match(periodRegex);
        if (match) {
          const start = parseInt(match[1], 10);
          const end = parseInt(match[2], 10);
          const periods = [];
          for (let i = start; i <= end; i++) {
            periods.push(`period${i}`);
          }
          return periods;
        }
        // 如果没有范围，尝试匹配单个节次
        const singlePeriodRegex = /(\d+)节/;
        const singleMatch = timeStr.match(singlePeriodRegex);
        if (singleMatch) {
          const period = parseInt(singleMatch[1], 10);
          return [`period${period}`];
        }
        return [];
      },
      getPeriodLabel(periodKey) {
        const period = this.periods.find((p) => p.value === periodKey);
        return period ? period.label : "";
      },
      cellStyle() {
        return { "text-align": "center" };
      },
      headerCellStyle() {
        return { "background-color": "#f5f7fa", "text-align": "center" };
      },
      openCourseDetails(course) {
        console.log('课程被点击:', course);
        this.selectedCourse = course;
        this.dialogVisible = true;
      },

      // 处理弹窗关闭
      handleClose(done) {
        // 可以在关闭前进行一些处理
        this.selectedCourse = null;
        done();
      },
    },
    mounted() {
      document.title = '学生信息管理系统'; // 动态设置页面标题
      const token = localStorage.getItem('token'); // 确保 token 已正确存储
      const userNo = sessionStorage.getItem('UserNo'); // 确保 UserNo 已正确存储
      if (!token || !userNo) {
        alert('缺少必要的认证信息，请重新登录。');
        this.$router.push({ name: "Login" });
      }
    },
  };
  const cyear = [
  {
    value: '24年秋',
    label: '24秋',
  },
  {
    value: '24年春',
    label: '24春',
  },
  {
    value: '23年秋',
    label: '23秋',
  },
  {
    value: '23年春',
    label: '23春',
  },
  {
    value: '22年秋',
    label: '22秋',
  },
  {
    value: '22年春',
    label: '22春',
  },
]
  </script>
  
  <style scoped>
  .course-table {
    padding: 20px;

  }
  .table{
    position: relative;
    top: 35px;
    left: 120px;
  }
  
  .course-item {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  padding: 5px;
  margin-bottom: 5px;
  height: 40px; /* 设置固定高度 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 省略溢出文本 */
  white-space: nowrap; /* 不换行 */
  cursor: pointer; /* 鼠标悬停时显示为指针 */
}

.course-item:hover {
  background-color: #bae7ff; /* 悬停时背景颜色变化 */
}
  .el-table .cell-content {
  height: 100px; /* 设置固定高度 */
  overflow: hidden; 
}
  
  .empty-slot {
    color: #bfbfbf;
    display:flex;
  }
  
  .empty-message {
    text-align: center;
    padding: 20px;
    color: #bfbfbf;
  }
  </style>